package com.lagou;

import com.lagou.component.Register;
import io.netty.channel.ChannelFuture;
import io.netty.util.internal.StringUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.lagou.handler.ServerHandler;
import com.lagou.request.RpcRequest;
import com.lagou.response.RpcResponse;
import com.lagou.utils.JSONDerializer;
import com.lagou.utils.JSONSerializer;
import com.lagou.utils.RpcDecoder;
import com.lagou.utils.RpcEncoder;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.util.concurrent.CountDownLatch;


@SpringBootApplication
public class ServerBootstrap {

    private static Register register = new Register();

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws InterruptedException {
        String ip = "127.0.0.1";
        int port = 8990;
        SpringApplication.run(ServerBootstrap.class, args);
        new Thread(() -> startServer(ip, port)).start();
        countDownLatch.await();
        register.register(ip + ":" + port);
    }

    /**
     * 启动服务器
     *
     * @param hostName 监听地址
     * @param port 监听端口
     */
    public static void startServer(String hostName, Integer port) {
        if (StringUtil.isNullOrEmpty(hostName) || port == null) {
            throw new IllegalArgumentException("hostName or port can't be null");
        }

        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONDerializer()));
                            pipeline.addLast(new RpcEncoder(RpcResponse.class, new JSONSerializer()));
                            pipeline.addLast(new ServerHandler());
                        }
                    });
            ChannelFuture sync = serverBootstrap.bind(hostName, port).sync();
            countDownLatch.countDown();
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

}
